package com.qut.graduate.busrtquery.ui.common;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.provider.Settings;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.NotificationCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.FileProvider;
import android.support.v7.widget.CardView;
import android.support.v7.widget.SwitchCompat;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.widget.CompoundButton;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.mikepenz.google_material_typeface_library.GoogleMaterial;
import com.qut.graduate.busrtquery.BRTQApp;
import com.qut.graduate.busrtquery.BRTQConstant;
import com.qut.graduate.busrtquery.BaseActivity;
import com.qut.graduate.busrtquery.BuildConfig;
import com.qut.graduate.busrtquery.R;
import com.qut.graduate.busrtquery.bean.ApkUpdate;
import com.qut.graduate.busrtquery.greendao.bean.BusLineCollect;
import com.qut.graduate.busrtquery.ui.MainActivity;
import com.qut.graduate.busrtquery.ui.user.LoginActivity;
import com.qut.graduate.busrtquery.utils.common.ApkVersionUtils;
import com.qut.graduate.busrtquery.utils.common.ContextUtils;
import com.qut.graduate.busrtquery.utils.common.LogUtils;
import com.qut.graduate.busrtquery.utils.net.HttpUtil;
import com.qut.graduate.busrtquery.utils.net.NetworkUtils;
import com.qut.graduate.busrtquery.utils.uiabout.ColorPaletteUtils;
import com.qut.graduate.busrtquery.utils.store.SPUtils;
import com.qut.graduate.busrtquery.utils.uiabout.StatusBarUtils;
import com.qut.graduate.busrtquery.utils.uiabout.ToastColorfulUtils;
import com.qut.graduate.busrtquery.view.MyDialogSureCancel;

import java.io.File;
import java.util.List;

import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.FindListener;
import top.wefor.circularanim.CircularAnim;
import uz.shift.colorpicker.LineColorPicker;
import uz.shift.colorpicker.OnColorChangedListener;

/**
 * 设置界面
 * 可以修改主题色、查看公告通知、地铁信息、琴岛通充值网点等
 *
 * @Author WLL
 * @Time: 2019/3/20 11:16
 */
public class SettingActivity extends BaseActivity implements View.OnClickListener {
    private static final String TAG = "SettingActivity";
    private Toolbar toolbar;
    private TextView toolbarTitle;
    private SwitchCompat mStatusBarSwitch;
    private LinearLayout mChangeThemeLayout;
//    private LinearLayout mApkUpdateLayout;
    private LinearLayout mNotificationLayout;
    private LinearLayout mSubwayInfoLayout;
    private LinearLayout mRechargeStationLayout;
    private LinearLayout mSettingActivityLayout;
    //    private SPUtils mSPUtils;
    private NotificationManager notificationManager;
    private Notification notification; // 下载通知进度提示
    private NotificationCompat.Builder builder;
//    File apkFile = null;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_setting;
    }

    @Override
    protected void init() {
//        mSPUtils = SPUtils.getInstance(getApplicationContext());
        initView();
        initEvent();
    }

    @Override
    public void onResume() {
        super.onResume();
        updateNowTheme();
    }

    @SuppressLint("ResourceAsColor")
    private void updateNowTheme() {
        toolbar.setPopupTheme(getPopupToolbarStyle());
        toolbar.setBackgroundColor(getPrimaryColor());
        toolbar.setTitle("");
        StatusBarUtils.fullScreen(this);
        updateBarColor();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    private void initEvent() {
        toolbarTitle.setText(R.string.setting);
        toolbar.setNavigationIcon(getToolbarIcon(GoogleMaterial.Icon.gmd_arrow_back));
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        mStatusBarSwitch.setChecked(preferenceUtils.getBoolean(getString(R.string.preference_translucent_status_bar), true));
        mStatusBarSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                preferenceUtils.putBoolean(getString(R.string.preference_translucent_status_bar), isChecked);
                updateTheme();
                setStatusBarColor();
                updateSwitchColor(mStatusBarSwitch, getAccentColor());
                mStatusBarSwitch.setText(isChecked ? "顶部状态栏透明" : "顶部状态栏不透明");
            }
        });
    }

    private void initView() {
        toolbar = findViewById(R.id.toolbar);
        toolbarTitle = findViewById(R.id.toolbar_title);
        setSupportActionBar(toolbar);

        mStatusBarSwitch = findViewById(R.id.translucent_status_bar_switch);
        mChangeThemeLayout = findViewById(R.id.change_theme_layout);
//        mApkUpdateLayout = findViewById(R.id.apk_update_layout);
        mNotificationLayout = findViewById(R.id.notification_layout);
        mSubwayInfoLayout = findViewById(R.id.subway_info_layout);
        mRechargeStationLayout = findViewById(R.id.recharge_station_layout);
        mSettingActivityLayout = findViewById(R.id.setting_layout);

        mChangeThemeLayout.setOnClickListener(this);
//        mApkUpdateLayout.setOnClickListener(this);
        mNotificationLayout.setOnClickListener(this);
        mSubwayInfoLayout.setOnClickListener(this);
        mRechargeStationLayout.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.change_theme_layout:
                primaryColorPiker();
                break;
//            case R.id.apk_update_layout:
//                apkUpdateQuery();
//                break;
            case R.id.notification_layout:
                gotoConvenient(BRTQConstant.CONVENIENT_TYPE_NOTICE);
                break;
            case R.id.subway_info_layout:
                gotoConvenient(BRTQConstant.CONVENIENT_TYPE_SUBWAY);
                break;
            case R.id.recharge_station_layout:
                gotoConvenient(BRTQConstant.CONVENIENT_TYPE_RECHARGE);
                break;
        }
    }

    public void gotoConvenient(int type) {
        Intent intent = new Intent(SettingActivity.this, ConvenientActivity.class);
        intent.putExtra("ConvenientType", type);
        startActivity(intent);
    }

    private void primaryColorPiker() {
        final AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this, getDialogStyle());

        final View dialogLayout = getLayoutInflater().inflate(R.layout.layout_color_piker_primary, null);
        final LineColorPicker colorPicker = dialogLayout.findViewById(R.id.color_picker_primary);
        final LineColorPicker colorPicker2 = dialogLayout.findViewById(R.id.color_picker_primary_2);
        final TextView dialogTitle = dialogLayout.findViewById(R.id.cp_primary_title);
        CardView dialogCardView = dialogLayout.findViewById(R.id.cp_primary_card);
        dialogCardView.setCardBackgroundColor(getCardBackgroundColor());

        colorPicker.setColors(ColorPaletteUtils.getBaseColors(getApplicationContext()));
        for (int i : colorPicker.getColors())
            for (int i2 : ColorPaletteUtils.getColors(getBaseContext(), i))
                if (i2 == getPrimaryColor()) {
                    colorPicker.setSelectedColor(i);
                    colorPicker2.setColors(ColorPaletteUtils.getColors(getBaseContext(), i));
                    colorPicker2.setSelectedColor(i2);
                    break;
                }

        dialogTitle.setBackgroundColor(getPrimaryColor());

        colorPicker.setOnColorChangedListener(new OnColorChangedListener() {
            @Override
            public void onColorChanged(int c) {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                    if (isTranslucentStatusBar()) {
                        getWindow().setStatusBarColor(ColorPaletteUtils.getObscuredColor(getPrimaryColor()));
                    } else getWindow().setStatusBarColor(c);
                }
                toolbar.setBackgroundColor(c);
                //mSettingActivityLayout.setBackgroundColor(colorPicker2.getColors()[0]);
                dialogTitle.setBackgroundColor(c);
                colorPicker2.setColors(ColorPaletteUtils.getColors(getApplicationContext(), colorPicker.getColor()));
                colorPicker2.setSelectedColor(colorPicker.getColor());
            }
        });
        colorPicker2.setOnColorChangedListener(new OnColorChangedListener() {
            @SuppressLint("ResourceAsColor")
            @Override
            public void onColorChanged(int c) {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                    if (isTranslucentStatusBar()) {
                        getWindow().setStatusBarColor(ColorPaletteUtils.getObscuredColor(c));
                    } else getWindow().setStatusBarColor(c);
                    if (isNavigationBarColored())
                        getWindow().setNavigationBarColor(c);
                    else
                        getWindow().setNavigationBarColor(ContextCompat.getColor(getApplicationContext(), R.color.md_black_1000));
                }
                toolbar.setBackgroundColor(c);
                dialogTitle.setBackgroundColor(c);
            }
        });
        dialogBuilder.setView(dialogLayout);

        dialogBuilder.setNeutralButton(getString(R.string.cancel).toUpperCase(), new DialogInterface.OnClickListener() {
            @SuppressLint("ResourceAsColor")
            @Override
            public void onClick(DialogInterface dialog, int which) {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                    if (isTranslucentStatusBar()) {
                        getWindow().setStatusBarColor(ColorPaletteUtils.getObscuredColor(getPrimaryColor()));
                    } else getWindow().setStatusBarColor(getPrimaryColor());
                }
                toolbar.setBackgroundColor(getPrimaryColor());
                dialog.cancel();
            }
        });

        dialogBuilder.setPositiveButton(getString(R.string.ok_action).toUpperCase(), new DialogInterface.OnClickListener() {
            @SuppressLint("ResourceAsColor")
            public void onClick(DialogInterface dialog, int which) {
                preferenceUtils.putInt(getString(R.string.preference_primary_color), colorPicker2.getColor());
                int position = 0;
                for (int i : colorPicker.getColors())
                    for (int j = 0; j < ColorPaletteUtils.getColors(getBaseContext(), i).length; j++)
                        if (ColorPaletteUtils.getColors(getBaseContext(), i)[j] == colorPicker2.getColor()) {
                            position = j;
                            Log.d("colorPicker position: ", position + "");
                            break;
                        }

                preferenceUtils.putInt(getString(R.string.preference_window_background_color), colorPicker2.getColors()[0]);
                if (position > 3) {
                    preferenceUtils.putInt(getString(R.string.preference_text_color), R.color.white);
                } else {
                    preferenceUtils.putInt(getString(R.string.preference_text_color), R.color.colorTextBlack);
                }
                updateTheme();
                setNavBarColor();
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                    if (isTranslucentStatusBar()) {
                        getWindow().setStatusBarColor(ColorPaletteUtils.getObscuredColor(getPrimaryColor()));
                    } else {
                        getWindow().setStatusBarColor(getPrimaryColor());
                    }
                }
            }
        });

        dialogBuilder.setOnDismissListener(new DialogInterface.OnDismissListener() {
            @SuppressLint("ResourceAsColor")
            @Override
            public void onDismiss(DialogInterface dialog) {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                    if (isTranslucentStatusBar()) {
                        getWindow().setStatusBarColor(ColorPaletteUtils.getObscuredColor(getPrimaryColor()));
                    } else getWindow().setStatusBarColor(getPrimaryColor());
                    if (isNavigationBarColored())
                        getWindow().setNavigationBarColor(getPrimaryColor());
                    else
                        getWindow().setNavigationBarColor(ContextCompat.getColor(getApplicationContext(), R.color.md_black_1000));
                }
                toolbar.setBackgroundColor(getPrimaryColor());
            }
        });
        dialogBuilder.show();
    }

    //    public void apkUpdateQuery() {
//        if (!(NetworkUtils.getNetworkType(this) == BRTQConstant.NETWORK_NONE)) {
//            BmobQuery<ApkUpdate> categoryBmobQuery = new BmobQuery<>();
//            categoryBmobQuery.addWhereEqualTo("objectId", "CATk7778");
//            categoryBmobQuery.findObjects(new FindListener<ApkUpdate>() {
//                @Override
//                public void done(final List<ApkUpdate> object, BmobException e) {
//                    if (e == null && object != null && object.size() > 0) {
//                        if (ApkVersionUtils.getVersionCode() <= object.get(0).getVersionCode()
//                                && ApkVersionUtils.getVersionName().compareTo(object.get(0).getVersionName()) < 0) {
//                            final MyDialogSureCancel myDialogSureCancel = new MyDialogSureCancel(mContext);
//                            myDialogSureCancel.getTitleView().setBackgroundResource(R.mipmap.dialog_title_bg);
//                            myDialogSureCancel.getContentView().setText("发\t现\t新\t版\t本");
//                            myDialogSureCancel.getSureView().setText("立即更新");
//                            myDialogSureCancel.getCancelView().setText("稍后再说");
//                            myDialogSureCancel.setCancelable(false);
//                            myDialogSureCancel.getSureView().setOnClickListener(new View.OnClickListener() {
//                                @Override
//                                public void onClick(View v) {
//                                    initNotification();
//                                    HttpUtil.getInstance().download(object.get(0).getApkFile().getFileUrl(),
//                                            BRTQConstant.APK_DIR, object.get(0).getApkFile().getFilename(),
//                                            SettingActivity.this);
//                                    myDialogSureCancel.cancel();
//                                }
//                            });
//                            myDialogSureCancel.getCancelView().setOnClickListener(new View.OnClickListener() {
//                                @Override
//                                public void onClick(View v) {
//                                    myDialogSureCancel.cancel();
//                                }
//                            });
//                            myDialogSureCancel.show();
//                        } else ToastColorfulUtils.info("当前已经是最新的版本!");
//                    }
//                }
//            });
//        } else ToastColorfulUtils.info("网络未连接");
//    }

//    // 初始化通知
//    private void initNotification() {
//        notificationManager = (NotificationManager) ContextUtils.getContext().getSystemService(Context.NOTIFICATION_SERVICE);
//        // 8.0 以后需要加上channelId 才能正常显示
//        String channelId = "detachment_w";
//        String channelName = "BRTQuery通知";
//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
//            NotificationChannel mChannel = new NotificationChannel(channelId, channelName, NotificationManager.IMPORTANCE_HIGH);
//            notificationManager.createNotificationChannel(mChannel);
//        }
//        builder = new NotificationCompat.Builder(ContextUtils.getContext(), "default");
//        builder.setContentTitle("正在下载...") // 设置通知标题
//                .setChannelId(channelId)
//                .setSmallIcon(R.mipmap.detachment_w)
//                .setLargeIcon(BitmapFactory.decodeResource(ContextUtils.getContext().getResources(), R.mipmap.detachment_w)) // 设置通知的大图标
//                .setDefaults(Notification.DEFAULT_LIGHTS) // 设置通知的提醒方式： 呼吸灯
//                .setPriority(NotificationCompat.PRIORITY_MAX) // 设置通知的优先级：最大
//                .setAutoCancel(false) // 设置通知被点击一次是否自动取消
//                .setContentText("下载进度: 0%")
//                .setProgress(100, 0, false);
//        notification = builder.build();//构建通知对象
//    }
//
//    @Override
//    public void onDownloadSuccess(File file) {
//        LogUtils.d("下载apk文件：  onSuccess: 下载完成" + file.getPath() + file.getName());
//        builder.setContentTitle("下载完成")
//                .setContentText("点击安装")
//                .setAutoCancel(true); // 设置通知被点击一次是否自动取消
//        notification = builder.build();
//        notificationManager.notify(1, notification);
//        apkFile = file;
//        checkIsAndroidO();
//    }

//    @Override
//    public void onDownloading(int progress) {
//        LogUtils.d("下载apk文件：  downloadProgress: " + progress);
//        builder.setProgress(100, progress, false);
//        builder.setContentText("下载进度: " + progress + "%");
//        notification = builder.build();
//        notificationManager.notify(1, notification);
//    }
//
//    @Override
//    public void onDownloadFailed(Exception e) {
//        LogUtils.d("下载apk文件异常：" + e);
//        builder.setContentTitle("下载失败")
//                .setAutoCancel(true); // 设置通知被点击一次是否自动取消
//        notification = builder.build();
//        notificationManager.notify(1, notification);
//    }
//
//    /**
//     * 安装apk
//     */
//    private void installApk(File file) {
//        Intent intent = new Intent();
//        intent.setAction(Intent.ACTION_VIEW);
//        intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
//        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
//            Uri contentUri = FileProvider.getUriForFile(mContext, BuildConfig.APPLICATION_ID + ".fileprovider", file);
//            intent.setDataAndType(contentUri, "application/vnd.android.package-archive");
//        } else {
//            // 通过Intent安装APK文件
//            intent.setDataAndType(Uri.parse("file://" + file.toString()), "application/vnd.android.package-archive");
//        }
//        if (mContext.getPackageManager().queryIntentActivities(intent, 0).size() > 0) {
//            mContext.startActivity(intent);
//        }
//        notificationManager.cancel(1); // 取消通知
//    }

//    /*
//     * 判断是否是8.0,8.0 需要处理未知应用来源权限问题,否则直接安装
//     */
//    private void checkIsAndroidO() {
//        if (Build.VERSION.SDK_INT >= 26) {
//            boolean canInstallApk = getPackageManager().canRequestPackageInstalls();
//            if (canInstallApk) installApk(apkFile);
//            else  // 请求安装未知应用来源的权限
//                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.REQUEST_INSTALL_PACKAGES},
//                        BRTQConstant.INSTALL_PACKAGES_REQUEST_CODE);
//        } else installApk(apkFile);
//    }


//    /**
//     * 申请权限回调
//     */
//    @Override
//    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
//        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
//        switch (requestCode) {
//            case BRTQConstant.INSTALL_PACKAGES_REQUEST_CODE:
//                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
//                    if (apkFile != null)
//                        installApk(apkFile);
//                } else {
//                    // 引导用户手动开启安装权限
//                    Intent intent = new Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES);
//                    startActivityForResult(intent, 1);
//                }
//                break;
//        }
//    }

//    /**
//     * 将用户引导至安装未知应用界面，允许安装未知应用后，回到当前activity继续安装应用
//     *
//     * @param requestCode requestCode
//     * @param resultCode  resultCode
//     * @param data        data
//     */
//    @Override
//    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
//        super.onActivityResult(requestCode, resultCode, data);
//        if (ActivityCompat.checkSelfPermission(ContextUtils.getContext(), Manifest.permission.REQUEST_INSTALL_PACKAGES)
//                == PackageManager.PERMISSION_GRANTED) {
//            if (apkFile != null)
//                installApk(apkFile);
//        }
//    }

}
